/*
 * Copyright (c) 2011, Will Strohl
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list 
 * of conditions and the following disclaimer.
 * 
 * Redistributions in binary form must reproduce the above copyright notice, this 
 * list of conditions and the following disclaimer in the documentation and/or 
 * other materials provided with the distribution.
 * 
 * Neither the name of WillStrohl.com nor the names of its contributors may be used 
 * to endorse or promote products derived from this software without specific prior 
 * written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Globalization;
using System.Text;
using System.Web.UI;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Security;
using DotNetNuke.UI.Skins.Controls;

namespace DotNetNuke.Modules.WillStrohlDisqus
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The ViewWillStrohlDisqus class displays the content
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class View : WillStrohlDisqusModuleBase, IActionable
    {

        #region Private Properties

        private int AttachedModule { get; set; }
        private string ApplicationName { get; set; }

        #endregion

        #region Event Handlers

        /// <summary>
        /// OnInit - initialization of the module
        /// </summary>
        /// <param name="e"></param>
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.PageLoad);
        }
        
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// -----------------------------------------------------------------------------
        private void PageLoad(object sender, System.EventArgs e)
        {
            try
            {
                if (!this.IsPostBack) this.BindData();
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        #endregion

        #region Private Helper Methods

        private void BindData()
        {
            this.LocalizeModule();

            if (this.Settings["ApplicationName"] != null)
                this.ApplicationName = this.Settings["ApplicationName"].ToString();

            if (this.Settings["AttachedModuleId"] != null)
                this.AttachedModule = int.Parse(this.Settings["AttachedModuleId"].ToString(), NumberStyles.Integer);

            bool blnReady = (this.AttachedModule > 0 && string.IsNullOrEmpty(this.ApplicationName) == false);

            if (this.AttachedModule < 1)
            {
                DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, this.GetLocalizedString("NoModuleAttached.Text"), ModuleMessage.ModuleMessageType.YellowWarning);
            }

            if (string.IsNullOrEmpty(this.ApplicationName))
            {
                DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, this.GetLocalizedString("NoApplicationName.Text"), ModuleMessage.ModuleMessageType.YellowWarning);
            }
            
            if (blnReady)
            {
                this.phScript.Controls.Add(new LiteralControl(this.GetDisqusScript()));
            }
        }

        private void LocalizeModule()
        {
            // do nothing
        }

        private string GetDisqusScript()
        {
            var sb = new StringBuilder(50);

            sb.Append("<script type=\"text/javascript\" language=\"javascript\">");
            sb.Append("(function ($, Sys) { ");
            sb.Append("function setupDnnSiteSettings() { ");
            sb.AppendFormat("var newModule = jQuery('.DnnModule-{0}'); ", this.AttachedModule);
            sb.Append("if (newModule.hasClass('DnnModule-Blog')) { ");
            sb.Append("jQuery('div.BlogFooterRight a[id$=\\'_lnkComments\\']').remove();");
            sb.Append("jQuery('div[id$=\\'_MainView_ViewEntry_pnlComments\\']').remove();");
            sb.Append("jQuery('div[id$=\\'_MainView_ViewEntry_pnlAddComment\\']').remove();");
            sb.Append("}");
            sb.AppendFormat("jQuery('.DnnModule-{0}').insertAfter('.DnnModule-{1}'); ", this.ModuleId, this.AttachedModule);
            sb.Append("} ");
            sb.Append("jQuery(document).ready(function (){ ");
            sb.Append("setupDnnSiteSettings(); ");
            sb.Append("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () { ");
            sb.Append("setupDnnSiteSettings(); ");
            sb.Append("}); ");
            sb.Append("}); ");
            sb.Append("} (jQuery, window.Sys)); ");
            sb.Append("</script>");
            
            sb.Append("<div id=\"disqus_thread\"></div>");
            sb.Append("<script type=\"text/javascript\" language=\"javascript\">");
            
            //sb.Append("/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */");
            sb.AppendFormat("var disqus_shortname = '{0}'; ", this.ApplicationName);

            //sb.Append("// The following are highly recommended additional parameters. Remove the slashes in front to use.");
            // need to parse for isolated views in DNN and add them to this identifier
            sb.AppendFormat("var disqus_identifier = 'wnsdisqus-{0}::{1}::{2}::{3}'; ", this.TabId, this.TabModuleId, this.PortalSettings.GUID, Request.RawUrl);
            sb.Append("var disqus_url = document.URL; ");
            /*if (Request.IsSecureConnection)
            {
                sb.AppendFormat("var disqus_url = 'https://{0}{1}'; ", this.PortalSettings.PortalAlias.HTTPAlias, Request.RawUrl);
            }
            else
            {
                sb.AppendFormat("var disqus_url = 'http://{0}{1}'; ", this.PortalSettings.PortalAlias.HTTPAlias, Request.RawUrl);
            }*/

            //sb.Append("/* * * DON'T EDIT BELOW THIS LINE * * */");
            sb.Append("(function() { ");
            sb.Append("var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; ");
            sb.Append("dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js'; ");
            sb.Append("(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); ");
            sb.Append("})();");
            sb.Append("</script>");
            sb.Append("<noscript>Please enable JavaScript to view the <a href=\"http://disqus.com/?ref_noscript\">comments powered by Disqus.</a></noscript>");
            sb.Append("<!--<a href=\"http://disqus.com\" class=\"dsq-brlink\">blog comments powered by <span class=\"logo-disqus\">Disqus</span></a>-->");

            return sb.ToString();
        }

        #endregion

        #region IActionable Implementation

        /// <summary>
        /// ModuleActions - loads the actions menu with a custom menu item
        /// </summary>
        public ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();
                Actions.Add(GetNextActionID(), Localization.GetString("EditModule", this.LocalResourceFile), "", "", "", EditUrl(), false, SecurityAccessLevel.Edit, true, false);
                return Actions;
            }
        }

        #endregion

    }

}
